<?php

namespace backend\modules\rbac\models;

use backend\modules\cache\models\CacheData;
use common\lib\LRtree;
use common\lib\TreeTrait;
use Yii;
use yii\base\Exception;
use yii\redis\Cache;

/**
 * This is the model class for table "menu".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent
 * @property string $route
 * @property integer $order
 * @property resource $data
 * @property integer $lft
 * @property integer $rgt
 * @property integer $lev
 * @property string $url
 * @property string $icon_char
 * @property string $dr
 * @property string $grade
 *
 * @property Menu $parent0
 * @property Menu[] $menus
 */
class Menu extends \yii\db\ActiveRecord
{
    use TreeTrait;

    public $filterWhere;

    public $pk = 'menu_id';

    public $typefilter = 'menu_type';

//    public $name = 'menu_name';

    public $menu_prev;

    public $prev = 'menu_prev';

    public $menu_next;

    public $next = 'menu_next';
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'menu';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent', 'order', 'lft', 'rgt', 'lev','dr','grade'], 'integer'],
//            [['data'], 'string'],
            [['name'], 'string', 'max' => 128],
            [['route', 'url', 'icon_char'], 'string', 'max' => 255],
            [['parent'], 'exist', 'skipOnError' => true, 'targetClass' => Menu::className(), 'targetAttribute' => ['parent' => 'id']],
        ];
    }

    public function setLeftAndRightColumn()
    {
        return ["lft", "rgt"];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Name'),
            'parent' => Yii::t('app', 'Parent'),
            'route' => Yii::t('app', 'Route'),
            'order' => Yii::t('app', 'Order'),
            'data' => Yii::t('app', 'Data'),
            'lft' => Yii::t('app', 'Lft'),
            'rgt' => Yii::t('app', 'Rgt'),
            'lev' => Yii::t('app', 'Lev'),
            'url' => Yii::t('app', 'Url'),
            'icon_char' => Yii::t('app', 'Icon Char'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParent0()
    {
        return $this->hasOne(Menu::className(), ['id' => 'parent']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenus()
    {
        return $this->hasMany(Menu::className(), ['parent' => 'id']);
    }

    /**
     * @inheritdoc
     * @return \backend\modules\rbac\models\query\MenuQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \backend\modules\rbac\models\query\MenuQuery(get_called_class());
    }

    public $permssionARR;
    /**
     * 获取用户角色
     *
     * @return array
     */
    public static function getPermissionMneuByUser()
    {
        $userid = Yii::$app->getUser()->id;
        $roles = AuthAssignment::findAll(['user_id'=>$userid]);
        $permssionARR = array();
        foreach($roles as $k=>$v){
            $newARR = array();
            $authItemChildARR = AuthItemChild::find()->select(['child'])->where(['parent'=>$v->item_name])->asArray()->all();
            foreach($authItemChildARR as $k=>$v) {
                $newARR[] = $v['child'];
            }
            $permssionARR = array_unique(array_merge($permssionARR,$newARR));
        }
        return $permssionARR;
    }

    /**
     * example：Yii2 AR模型的查询条件格式
     * return ['<','grade',3];
     * 无限分类树数据表前置查询条件
     * @return array
     */
    public function preCondition()
    {
        return [];
    }


    /**
     *
     *
     * [
    'label' => '商品管理',
    'icon' => 'share',
    'url' => '#',
    'items' => [
    ['label' => '商品列表', 'icon' => 'file-code-o', 'url' => ['/goods/goods/index'],],
    ['label' => '商品分类', 'icon' => 'file-code-o', 'url' => ['/goods/attrcat/index'],],
    ['label' => '商品属性', 'icon' => 'file-code-o', 'url' => ['/goods/attribute/index'],],
    ]
    ],
     */
    public function getLeftMenu()
    {
        $code = 'menu'.\Yii::$app->user->identity->code;
        $permssionARR = static::getPermissionMneuByUser();
        foreach($permssionARR as $k=>$v) {
            $permssionARR[$k] = str_replace("Menu@","",$v);
        }
        $this->permssionARR = $permssionARR;
        //缓存
        $cache = new Cache();
        $leftMenu = $cache->get($code);
        if($leftMenu){
            return $leftMenu;
        }
        $newMenu = new Menu();
        $treeList = $newMenu->tree_list();
        $leftMenu = $this->ViewCate($treeList);
        if(!$leftMenu){
            die('您无权限登录系统，请联系管理员并申请权限！');
        }
        //缓存新数据
        if(!$cache->set($code,$leftMenu)){
            return  false;
        }
        return $leftMenu;
    }


    public function ViewCate($menu)
    {
        foreach ($menu as $v => $k) {
            if(!in_array($k->id,$this->permssionARR)){
                continue;
            }
            if (isset($k->tree_children) ) {
                $arrRe[] = ['label' => $k->name, 'icon' => $k->icon_char, 'url' => '#','items'=> $this->ViewCate($k['tree_children'])];
            }
            else {
                $arrRe[] = ['label' => $k->name, 'icon' => $k->icon_char, 'url' => [$k->url]];
            }
        }
        return isset($arrRe)?$arrRe:[];
    }

    public function multiSave($post)
    {
        $error = array();
        $transaction = $this->getDb()->beginTransaction();
        try {
            $tree = new LRtree($this);
            try {
                if(!$this->isNewRecord){
                    $this->updataParent($this, $this->parent);
                }
                $tree->node();
            } catch (\yii\base\Exception $e) {
                throw new Exception($e->getMessage());
            }

            if(!$this->isNewRecord){
                $transaction->commit();
                $menu = Menu::findOne(['id'=>$this->id]);
                $tree->HorMove($menu);
                return true;
            }else{
                if ($this->load($post,'')&&$this->save()) {
                    //创建menu权限
                    $newMenuPerm = new MenuPerm;
                    $newMenuPerm->createItemMenu($this->id);
                    $transaction->commit();
                    return [true,'操作成功'];
                } else {;print_r($this->errors);exit;
                    return [false,$this->getErrorsToSting($this->errors)];
                }
            }

        } catch (Exception $e) {
            $transaction->rollBack();
            $error[] = array_merge([$e->getMessage()], $this->errors);
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param $model
     * @param $parent
     * @throws \yii\db\Exception
     */
    public function updataParent($model,$parent){
        $sql = "update
        {$this->tableName()}
        set parent = '{$parent}'
        where lft = {$model->lft}";

        Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 将数组转换成字符串
     * @param array $errors
     * @return string|unknown
     */
    public function getErrorsToSting($errors){
        $str ='';
        foreach ($errors as $key=>$val)
        {
            $str .= $val[0];
        }

        return $str;
    }
}
